﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Linq;
using Twipler.App.Machine;
using Twipler.App.Parse.Code;
using Twipler.App.Render.Tree;

namespace Twipler.App.Parse.Html.Consumers
{
    [Consumer(OpenTag="doc", CloseTag="docend", Parameters = typeof(DocParams))]
    public class DocConsumer : TemplateConsumer
    {
        public class DocParams : TemplateParameters
        {
            [HtmlArgument(TokenParser.TokenType.ItemName, false)]
            public string Name;

            [HtmlArgument(TokenParser.TokenType.StaticMethodCall, false)]
            public StaticMethodCall Source;

            [HtmlArgument(TokenParser.TokenType.TimeSpan, true)] 
            public TimeSpan? CacheDuration;
        }

        public DocConsumer()
        {
            Parameters = new DocParams();
        }

        public override AbstractItem Process(Template template, TemplateConsumer parent)
        {
            ReadArguments(template);
            if (template.HasErrors)
                return ParseErrorItem.Create(template.Errors.First().Message);

            template.SkipWhiteSpace();
            if (template.Peek(Template.EndMarker, false) == false)
                return Error(template, "Missing template close tag (" + Template.EndMarker + ")");

            template.SkipOver(Template.EndMarker);

            string tag = string.Empty;
            AbstractItem renderItem = template.ParseUntil(new string[] { "docend" }, ref tag, this);
            if (tag != string.Empty)
                template.SkipOver(Template.EndMarker);

            return DocItem.Create(renderItem, ((DocParams)Parameters).Name, ((DocParams)Parameters).Source, ((DocParams)Parameters).CacheDuration);
        }
    }
}